package net.phoenix.repository.query.jql;

import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.qom.Comparison;
import javax.jcr.query.qom.DynamicOperand;
import javax.jcr.query.qom.EquiJoinCondition;
import javax.jcr.query.qom.StaticOperand;

/**
 * 
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-4-22
 * @version 1.0.0
 */
public class ComparisonAST extends ConstraintAST implements Comparison, EquiJoinCondition {

	public ComparisonAST() {
		super();
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1220277354572734089L;

	@Override
	public DynamicOperand getOperand1() {
		return (DynamicOperand) this.getFirstChild();
	}

	@Override
	public String getOperator() {
		return this.getText();
	}

	@Override
	public StaticOperand getOperand2() {
		if (this.getNumberOfChildren() == 1)
			return null;
		return (StaticOperand) this.getFirstChild().getNextSibling();

	}

	@Override
	public String getSelector1Name() {
		DotExpressionAST expr = (DotExpressionAST) this.getFirstChild();
		return expr.getSelectorName();
	}

	@Override
	public String getProperty1Name() {
		DotExpressionAST expr = (DotExpressionAST) this.getFirstChild();
		return expr.getPropertyName();
	}

	@Override
	public String getSelector2Name() {
		DotExpressionAST expr = (DotExpressionAST) this.getFirstChild().getNextSibling();
		return expr.getSelectorName();
	}

	@Override
	public String getProperty2Name() {
		DotExpressionAST expr = (DotExpressionAST) this.getFirstChild().getNextSibling();
		return expr.getPropertyName();
	}

	@Override
	public String toJQL() {
		StringBuffer buffer = new StringBuffer();
		JQLBaseAST child = (JQLBaseAST) this.getFirstChild();
		buffer.append(child.toJQL());
		buffer.append(" ");
		buffer.append(this.getText());
		buffer.append(" ");
		if (child.getNextSibling() != null)
			buffer.append(((JQLBaseAST) child.getNextSibling()).toJQL());
		return buffer.toString();
	}

	@Override
	public void generateSQL(JQL2SQL collector) throws InvalidQueryException{
		JQLBaseAST first = (JQLBaseAST) this.getFirstChild();
		first.generateSQL(collector);
		JQLBaseAST second = (JQLBaseAST) first.getNextSibling();
		StringBuffer where = new StringBuffer();
		if (second != null) {
			second.generateSQL(collector);
			where.append(collector.pop());
			where.insert(0, " ");
		}
		where.insert(0, this.getText());
		where.insert(0, " ");
		where.insert(0, collector.pop());
		collector.push(where.toString());
	}
}
